<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class OrderRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'address_id' => 'required',
            'payment_method' => 'required',
            'deliver_type' => 'required',
        ];
    }

    public function withValidator($validator)
    {

    	$validator->after(function ($validator) {
    		$goods = $this->user()->carts()->with('goods')->get();
	        foreach($goods as $v)
	        {
	        	if(!$v->goods)
	        	{
	        		$validator->errors()->add('notexits', '商品不存在或已下架');
	        	}

	            if($v->goods->status == 0)
	            {
	                $validator->errors()->add('off', $v->goods->name.'商品已下架');
	            }

	            if($v->quantity > $v->goods->stock) {
	            	$validator->errors()->add('outstock', $v->goods->name.'没有足够库存');
	            }
	        }
        });
    }
}
